package ua.races.command.implementation;

import ua.races.command.ServletCommand;
import ua.races.dao.RacesDaoImpl;
import org.apache.log4j.Logger;
import ua.races.dao.RacesDaoImpl;
import ua.races.vo.Bet;
import ua.races.vo.Client;
import ua.races.vo.Race;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

/**
 * This command is for client's authorization
 */
public class ClientCheckCommand implements ServletCommand {

    private static final Logger log = Logger.getLogger(ClientCheckCommand.class.getName());

    public void execute(HttpServletRequest req, HttpServletResponse resp, ServletContext context) {

        final String email = req.getParameter("email").trim();
        final long password = req.getParameter("password").hashCode();
        final Client client;
        final HttpSession session;
        final String redirectUrl;
        final String message;
        log.info("Client authentification");

        try {
            RacesDaoImpl dao = (RacesDaoImpl) context.getAttribute("DAO");
            client = dao.findClientByEmail(email);

            if ((client != null) && (client.getPassword() == password)) {

                req.getSession(true).setAttribute(SESS_AUTH, Boolean.TRUE);
                message = "Authorized!";
                redirectUrl = "prepareClient.do";
                session = req.getSession(true);
                session.setAttribute("client", client);
//                List<Bet> bets = dao.findAllClientBets(client);
//                session.setAttribute("bets", bets);
//                // todo List<Race> races = dao.findAllRacesForBet();
//                List<Race> races = dao.findAllRaces();
//                session.setAttribute("races", races);
                log.info("Client : " + client.getLastName() + " " + client.getFirstName() +
                        " just has come to his account");

            } else {
                log.info("Attempt to authorize was unsuccessful");
                message = "Not Authorized!";
                redirectUrl = "index.jsp";
            }

            req.setAttribute("message", message);
            req.setAttribute("URL", redirectUrl);
            context.getRequestDispatcher("/redirection.jsp").forward(req, resp);

        } catch (SQLException e) {
            log.error(e);
        } catch (ServletException e) {
            log.error(e);
        } catch (IOException e) {
            log.error(e);
        }
    }
}


